/**
 * @class Digu
 * @fileOverview 嘀咕微博控制器
 * @extends yijs.air.Controller
 */ 
var Digu = function(user){
	//配置信息
	this.config			  = yijs.config.digu || {};
	//ajax预加载时显示的信息
	this.ajaxMsgs 		 = yijs.lang.ajaxMsg;
	this.ajaxGetMsg      = this.ajaxMsgs.get;
	this.ajaxCompleteMsg = this.ajaxMsgs.complete;	
	//样式
	this.cls = this.config.cls;
	//切换特效
	this.effect = this.config.effect;
	//每个动作容器的样式类名		
	this.actionCls = this.config.actionCls;
	//服务器端返回数据的字段
	this.field = this.config.field || {};
	//模型
	this.ModelOption	  = new Option();
	//一页数据数
	this.limitNum = Number(this.ModelOption.get("number"));
	this.ModelTemp  	  = new Temp();
	this.ModelMsg    	  = new Msg();
	//服务器端返回的数据类型
	this.type 			  = yijs.config.dataType[1];
	//语言
	this.lang 			  = yijs.lang.digu;
	//视图路径
	this.viewPath         = helpYi.getViewPath(yijs.config.viewName.digu);
	this.itemsViewPath    = helpYi.getViewPath(yijs.config.viewName.diguItems);
	//用户信息
	this.user             = user;
	this.authorization	  = _getAuthorization(this.user.name,this.user.password);
	
	this.ajaxApplyTo      = yijs.config.ajax.applyTo;
	this.id               = this.config.idPrefix+this.user.name;
	this.$main			  = null;
	this.contentContainer = "#"+this.id+" > "+this.config.contentContainer;
	this.$content         = null;
	this.CONTENT_WIDTH 	  = 0;
	this.$bottomNav = null;
	//控制器名
	this.controller		  = this.user.controller;
	
	//实例化ajax预加载动画类
	this.Preload		    = new yijs.Preload();
	this.Preload.defaultMSg = yijs.lang.ajaxMsg.defaultMSg;
	//实例化远程代理类
	this.Proxy				 = new yijs.proxy.Digu();
	this.Proxy.authorization = _getAuthorization(this.user.name,this.user.password);
	this.Proxy.count		 = this.config.count;
	this.Proxy.Preload 		 = this.Preload;
	//子控制器的配置信息
	this.childrenControllerConfig = {config : this.config,
									 lang   : this.lang,
									 Proxy  : this.Proxy,
									 contentContainer : this.contentContainer,
									 controller : this.controller}
	
	//获取http验证
	function _getAuthorization(name,password){
		var name 		  = name;
		var password      = password;
		var Authorization = "Basic " + Base64.encode(name+":"+password);
		return Authorization;		
	}
}

/**
 * 用户认证
 * @param {Object} Authorization 认证信息
 * @param {Object} success 认证成功后的回调函数
 */
Digu.prototype.verify = function(success){
		this.Proxy.verify(function(data){
			if(success) success.call(this,data);
		});
}
/**
 * 读取并解析模板
 */
Digu.prototype.view = function(){
	var _that = this;
	var langsXml = getLangXml(this.lang);
	yijs.air.view(langsXml,
				  {url:this.viewPath},"body",null,false,
				  function(renderTo,result){
				  		helpYi.viewChangeEffect.fade(renderTo,result);
						_that.viewHandler();
				  });
	
}
/**
 * 解析完模板后触发的事件
 * @param {Object} xml
 * @param {Object} xsl
 */
Digu.prototype.viewHandler = function(){
	var _that = this;
	//给容器添加id
	$("."+this.cls.main+":last").attr("id",this.id);
	this.$main	  = $("#"+this.id);
	//内容容器
	this.$content = this.$main.children("#"+this.contentContainer);
	//内容容器宽度
	this.CONTENT_WIDTH = this.$content.width();
	this.$bottomNav = this.$main.find("."+this.cls.bottom_nav_content).find("ul");
	_navHover();
	yijs.hover("."+this.cls.set+" > li",_that.cls.mySetLiHover);
	this.mainTopNavControll();
	this.nativeWindowControll();
	this.setNavHeaderSlide();
	//读取用户信息
	this.u();
	//!this.ModelMsg.isNull(this.user.controller,"userMsg") && this.getDbMsg("userMsg",1) ||	this.userMsg();
	this.friendsMsg(true);
	var _navCls = this.cls.nav;
	var _Friends = new c.Friends(this.childrenControllerConfig);
	this.$bottomNav.children("."+_navCls.msg).click(function(){
		_that.friendsMsg();		
	})
	this.$bottomNav.children("."+_navCls.square).click(function(){
		_that.publicMsg();
	})
	$(".friendList").bind("click",function(){
		_Friends.get();
	})	
		$("#MY_MSG").click(function(){
			_that.userMsg();
		})
		$("#FRIENDS_Msg").click(function(){
			_that.friendsMsg();	
		})	

	
	//鼠标移过移开菜单项
	function _navHover(){
		_that.$bottomNav.children("li").hover(function(){
			if(!$(this).hasClass(_that.cls.nav_li_current)){
				$(this).addClass(_that.cls.nav_li_hover);
			}
			var _w = $(this).outerWidth()+parseInt($(this).css("marginLeft"))+parseInt($(this).css("marginRight"));
			var _index = _that.$bottomNav.children("li").index($(this));
			var _gap =  _w * _index;
			var _effect = _that.effect.bottomNavMask;
			$("."+_that.cls.nav_li_mask).stop().animate({"left":_gap},_effect.duration,_effect.easing);
		},function(){
			if(!$(this).hasClass(_that.cls.nav_li_current)){
				$(this).removeClass(_that.cls.nav_li_hover);
			}		
		})		
	}
	
	
}
/**
 * 用户信息获取和显示
 */
Digu.prototype.u = function(){
	var _that = this;
	//请求时需要的参数
	var _param = this.user.name;
	var _preLoadMsg = _that.lang.user;	
	_get(_param,function(data){_set(data)});	
	/**
	 *获取用户数据 
	 * @param {String} _param 参数
	 * @param {Function} callback 成功获取数据后的回调函数
	 */
	function _get(_param,callback){
		//预加载信息		
		var _beforeSendMsg = yijs.setTpl(_that.ajaxMsgs.get,[_preLoadMsg]);
		var _successMsg = yijs.setTpl(_that.ajaxMsgs.complete,[_preLoadMsg]);		
		_that.Proxy.getUser(function(data){
			if(callback) callback.call(this,data);
		},_beforeSendMsg,_successMsg,_param);			
	}
	/**
	 * 显示用户数据
	 * @param {Object} data	待处理的数据
	 */
	function _set(data){
				var user 		= helpYi.xml2json($(data).find(_that.field.user));
				var _faceSizes  = _that.config.faceSizes;
				var _male   = _that.lang.male;
				var _female = _that.lang.female;
				var _$mainTop = _that.$main.children("."+_that.cls.main_top);
				var _$detail = _$mainTop.find("."+_that.cls.my_detalls);
				var _$face = _$mainTop.find("."+_that.cls.face);
				var _$username = _$mainTop.find("."+_that.cls.username);
				_$username.text(user["screen_name"]);
				_write(_that.cls.username,user["screen_name"]);
				_write(_that.cls.show_name,user["screen_name"]);
				_write(_that.cls.register_name,user["name"]);
				_write(_that.cls.location,user["location"]);
				_write(_that.cls.gender,Number(user["gender"]) == 1 && _male || _female);
				_write(_that.cls.followers_count,user["followers_count"]);
				_write(_that.cls.friends_count,user["friends_count"]);
				//修改头像大小（默认头像为24x24，过小了）
				var _face = user["profile_image_url"];
				var _reg = /24x24/;
				_face = _face.replace(_reg,_faceSizes[2]);
				_$face.children("img").attr("src",_face);
				_$detail.find("."+_that.cls.full_face).children("img").attr("src",user["profile_image_url"].replace(_reg,_faceSizes[1]));
				//写入缓存
				_$detail.data(user);
				
				function _write(cls,val){
					_$detail.find("."+cls).text(val);
				}			
	}
}
/**
 * 获取我的消息
 */
Digu.prototype.userMsg = function(isGetDb){
	//动作
	var _action = this.actionCls.userMsg;
	//预加载信息片段
	var _preLoadMsg = this.lang.myMsg;
	this.runAction("getUserMsg",isGetDb,_action,_preLoadMsg);
}
/**
 * 获取我和好友的消息
 */
Digu.prototype.friendsMsg = function(isGetDb){
	//动作
	var _action = this.actionCls.friendsMsg;
	//预加载信息片段
	var _preLoadMsg = this.lang.friendsMsg;
	this.runAction("getFriendsMsg",isGetDb,_action,_preLoadMsg);	
}
/**
 * 获取公共信息
 */
Digu.prototype.publicMsg = function(isGetDb){
	//动作
	var _action = this.actionCls.publicMsg;
	//预加载信息片段
	var _preLoadMsg = this.lang.publicMsg;
	this.runAction("getPublicMsg",isGetDb,_action,_preLoadMsg);		
}
/**
 * 运行动作
 * @param {String} proxy	  代理类的方法名
 * @param {Boolean} isGetDb	  是否直接读取数据库
 * @param {String} action	  动作名
 * @param {String} preLoadMsg 预加载信息
 * @param {Object} param	  参数
 */
Digu.prototype.runAction = function(proxy,isGetDb,action,preLoadMsg,param){
	var _that = this;
	var _param = param || {};
	//动作
	var _action = action;
	//清理缓存数据
	this.removeCacheData(_action);
	var _$action = $(this.contentContainer+" > ."+action);
	if(_$action.size() == 0){
		//创建该动作下的容器	
		_$action = _createActionContainer(_action);
		//创建分页器
		var _Slider = this.createSlider(_action,function(val){
			_that.getDbMsg(_action,val);
		});	
		if(isGetDb){
			//从数据库中读数据
			_that.getDbMsg(_action,0);
		}else{
			_that.runProxy(proxy,_action,_Slider,preLoadMsg,param);
		}
		//设置动作容器宽度
		_setActionContainerWidth();					
	}
	//滚动到当前动作容器
	_contentSlideTo(_$action);
	
	/**
	 * 创建动作下的信息容器 
	 * @param {String} action 动作名
	 * @return {Object} 该容器对象
	 */
	function _createActionContainer(action){
		var _actionVessel = _that.contentContainer+" > ."+action;
		var _$action = $(_actionVessel);
		_$action.size() == 0 && $("<div />",{"class":action + " "+_that.cls.actionItemsContainer}).appendTo(_that.contentContainer);
		return 	$(_actionVessel);
	}
	/**
	 * 设置动作容器宽度
	 */
	function _setActionContainerWidth(){
		var _$c = _that.$content.children();
		_$c.width(_that.CONTENT_WIDTH);
		_that.$content.width(_$c.size() * _$c.width());			
	}	
	/**
	 * 滑动内容容器
	 * @param {Object} $action 动作容器
	 */
	function _contentSlideTo($action){
		var _index = $("."+_that.cls.actionItemsContainer).index($action);
		var _marginLeft = _index == 0 && 0 || "-"+_index*_that.CONTENT_WIDTH;	
		var _effet = {duration:_that.effect.content.duration,easing: _that.effect.content.easing};
		_that.$content.animate({"marginLeft":_marginLeft},_effet);	
	}	
}
/**
 * 先读取服务器，将新的消息写入到数据库，最后从数据库获取消息，同时更新分页器
 * @param {Object} proxy
 * @param {Object} action
 * @param {Object} Slider
 * @param {Object} preLoadMsg
 * @param {Object} _param
 */
Digu.prototype.runProxy = function(proxy,action,Slider,preLoadMsg,_param){
	var _that = this;
	//预加载信息片段
	var _preLoadMsg = preLoadMsg;
	var _getMsg = this.ajaxGetMsg;
	var _completeMsg = this.ajaxCompleteMsg;
	//预加载信息
	_beforeSendMsg = yijs.setTpl(_getMsg,_preLoadMsg);
	_successMsg = yijs.setTpl(_completeMsg,_preLoadMsg);
	//读取数据
	this.Proxy[proxy](function(data){
		_that.insertDbMsg(action,data,function(){
				_that.getDbMsg(action,0);			
		});	
		var _max = _that.getMaxPage(action);
		Slider.reset(1,_max);				
	},_beforeSendMsg,_successMsg,_param)
	
}
/**
 * 创建分页滑动条
 * @param {String} action	动作
 */
Digu.prototype.createSlider = function(action,onslide){
	var _that = this;	
	var _$sliderRenderTo = this.contentContainer + " > " +"."+action;
	var _max = this.getMaxPage(action);
	var _Slider = new yijs.Slider({renderTo : _$sliderRenderTo,
								  width:100,
								  max:_max,
								  min:1,
								  listeners : {
								  	slide : function(val){
									   var _timer = setTimeout(function(){onslide && onslide.call(this,_Slider.value-1);clearTimeout(_timer)},700);
									}
								  }
								 });			
	_Slider.render();
	return 	_Slider;
}
/**
 * 获取最大页数
 * @param {Object} action
 */
Digu.prototype.getMaxPage = function(action){
	var _num = this.ModelMsg.getMsgsNum(this.controller,action);
	var _max = Math.ceil(_num/this.limitNum);
	return 	_max;
}
/**
 * 删除在动作容器上的数据缓存
 * @param {Object} action 动作名
 */
Digu.prototype.removeCacheData = function(action){
	var _max = this.getMaxPage(action);
	var $cache = $(this.contentContainer + " > " +"."+action);
	var _cacheName = null;
	for(var i = 0;i < _max ; i++){
		_cacheName = action+"_"+i;
		$cache.removeData(_cacheName);
	}
	return 	true;
}
/**
 * 从数据库读取消息
 * @param {String} action	动作
 * @param {Number} page	    指定页数
 */
Digu.prototype.getDbMsg = function(action,page){
	var _that = this;
	//容纳消息数据的容器
	var _renderTo = this.contentContainer+" > ."+action;
	var _cacheName = action+"_"+page;
	var _$renderTo = $(_renderTo);
	var _xml = null;
	if(_$renderTo.size() > 0){
		if(_$renderTo.data(_cacheName)){
			_xml = _$renderTo.data(_cacheName);
		}else{
			//读取数据
			var _start = page * this.limitNum;
			var data = this.ModelMsg.getAssignMsgs(this.user.controller,action,_start,this.limitNum);
			if(data && data.length > 0){
				//转成xml数据
				_xml = helpYi.json2xml(data,"statuses","status",function(key,value){
					//格式化日期输出
					if(key == "created_at"){
						var date = new Date(Number(value));
						var timer = helpYi.formatTime(date.toGMTString());
						return timer;
					}
					//格式化头像输出
					if(key == "user_profile_image_url"){
						var _face = helpYi.formatFace(value, _that.config.faceSizes[1]);
						return '<img src="'+_face+'" width="48" height="48" />';
					}
					return value;
				});
				//将数据写入缓存
				_$renderTo.data(_cacheName,_xml);			
			}		
		}
		 var _$ul = _$renderTo.children("ul");
		 removeLis(_$ul,100,function(){
			//读取视图，并解析模板
			yijs.air.view(_xml,{url:_that.itemsViewPath},_renderTo,function(xml,xsl){
				_viewHandler();	
			},true);		 	
		 });				
	}
	
	function removeLis($ul,delayTimer,fnCallBack){
		if($ul.size() > 0){
			var _$li = $ul.children("li"); 
			var _len = _$li.size();
			var _delayTimer = 0;
			_animate(_len-1);
			function _animate(eq){
				_$li.eq(eq).delay(_delayTimer).fadeOut("fast",function(){
					if(eq == 0){
						$ul.remove();
						fnCallBack && fnCallBack.call(this);
					}
				});
				if(eq == 0){
					return false;
				}else{
					_len = eq;
					_len --;	 
					_delayTimer += delayTimer;	
					_animate(_len);						
				}	
			}								
		}else{
			fnCallBack && fnCallBack.call(this);
		}
	}
	function _viewHandler(){
	    var $liOdd = _$renderTo.find("li:odd");
		$liOdd.addClass("status_odd");
		var $li = _$renderTo.find("li"); 
		var len = $li.size();
		var _delayTimer = 0;
		$li.each(function(){
			$(this).delay(_delayTimer).fadeIn("fast");
			_delayTimer += 200;
		})		
	}		
}
/**
 * 将消息插入到数据库
 * @param {String} action 		动作
 * @param {Object} data xml		数据源
 * @param {Function} fnCallBack 插入完成后回调函数
 * @return {Boolean}
 */
Digu.prototype.insertDbMsg = function(action,data,fnCallBack){
	var _controller = this.user.controller;
	var _action = action;
	//最后获取时间戳的key名
	var _lastGetTimerField = _controller + "_" + _action + "_" + "last_timer";
	var $status = $(data).find("status");
	var _size = $status.size();
	if(_size > 0){
		for(var i = _size-1 ;i >=0 ; i--){
				var _user = $status.eq(i).children("user");
				//将时间转化为时间戳
		        var date = new Date($status.eq(i).children("created_at").text());
				var _created_at = date.getTime();	
				//获取最后获取时间戳
				var _lastGetTimer = this.ModelTemp.get(_lastGetTimerField);
				//大于最后获取时间戳写入到数据库
				if(_created_at > _lastGetTimer){
					var _data = {controller             : _controller,action :_action,
					             msg_id                 : $status.eq(i).children("id").text(),
								 created_at             : _created_at,
								 text                   : $status.eq(i).children("text").text(),
								 source                 : $status.eq(i).children("source").text(),
								 user_id                : _user.children("id").text(),
								 user_name              : _user.children("name").text(),
								 user_screen_name       : _user.children("screen_name").text(),
								 user_location          : _user.children("location").text(),
								 user_description       : _user.children("description").text(),
								 user_profile_image_url : _user.children("profile_image_url").text(),
								 user_url               : _user.children("url").text(),
								 user_protected         : _user.children("protected").text()
					}
					this.ModelMsg.insert(_data);							
				}
				//更新最后获取时间戳
				i == 0 && this.ModelTemp.update(_lastGetTimerField,_created_at);		 			
		}
		if(fnCallBack) fnCallBack.call(this);
	}
	return true;			 
}
/**
 * 设置菜单子项的滑动
 */
Digu.prototype.setNavHeaderSlide = function(){
	var $slide = this.$main.find("."+this.cls.nav_header_slider);
	var ulWidth = $slide.parent().width();
	var $ul = $slide.children("ul");
	$ul.width(ulWidth);
	$slide.width(ulWidth * $ul.size());
	var _$nav = this.$main.find("."+this.cls.bottom_nav_content);
	var $li = _$nav.find("li");
	$li.mouseover(function(){
		var index = $li.index($(this));
		var marginLeft = index == 0 && 0 || "-" + index * ulWidth;
		$slide.stop().animate({"marginLeft": marginLeft},"fast");
	});
}
/**
 * 点击头像弹出设置菜单
 */
Digu.prototype.mainTopNavControll = function(){
	var _that = this;
	var _$nav = this.$main.find("."+this.cls.main_top_nav);
	var _$face = this.$main.find("."+this.cls.face);
	//双击头像，显隐菜单
	_$face.toggle(function(){_showMainTopNav();return false;},function(){_hideMainTopNav();return false;})
	_$nav.click(function(){return false;})
	$("body").click(function(){_hideMainTopNav();})
	//显示
	function _showMainTopNav(){
		var _effect = _that.effect.mainTopNavShow;
		_$nav.show(_effect.duration,_effect.easing);
	}
	//隐藏
	function _hideMainTopNav(){
		var _effect = _that.effect.mainTopNavHide;
		_$nav.hide(_effect.duration,_effect.easing);
	}	
}
/**
 * 窗体控制
 */
Digu.prototype.nativeWindowControll = function(){
	//关闭程序
	$("."+this.cls.nativeWindowControllerContainer+" > ."+this.cls.nativeWindowClose+"").click(function(){
		 nativeWindow && nativeWindow.close(); 
	})
	//最小化程序
	$("."+this.cls.nativeWindowControllerContainer+" > ."+this.cls.nativeWindowMini+"").click(function(){
		 nativeWindow && nativeWindow.minimize(); 
	})
	//拖放窗体
	this.$main.find("."+this.cls.main_top).bind("mousedown",function(e){
		var _position = {x:e.pageX,y:e.pageY};
		 nativeWindow.startMove() 
	})	
}


